﻿using System.Web.Mvc;
using System.Diagnostics;
//using CashFlow.b
using CashFlow.BusinessContracts;
using System.Web.Routing;
using CashFlow.BusinessComponents;
using CashFlow.Repository;
using CashFlow.AzureRepository;
using System;
using CashFlow.Entities.Models;
using CashFlow.Entities;

namespace CashFlow.Web.Controllers
{
	//[HandleError]
	public class CashFlowController : Controller
	{
		private ICashFlowComponent component;
		private ITenantRepository tenantRepository;
		private IBillRepository billRepository;

		#region Constructors
		public CashFlowController()
		{
		}

		public CashFlowController(
			ICashFlowComponent component,
			ITenantRepository tenantRepository,
			IBillRepository billRepository)
		{
			this.component = component;
			this.tenantRepository = tenantRepository;
			this.billRepository = billRepository;
			//com.TenantId = Environment.TenantId;
		}


		protected override void Initialize(RequestContext requestContext)
		{
			if (component == null)
			{
				//DEBUG
				var tenantId = Tenant.GetDefault().Id;
				tenantRepository = new AzureTenantRepository();
				billRepository = new AzureBillRepository();
				component = new CashFlowComponent();
			}

			base.Initialize(requestContext);
		}

		#endregion

		//
		// GET: /CashFlow/
		public ActionResult List()
		{
			return View();
		}

		public ActionResult Refresh(string month)
		{
			var model = FakeData.CashFlowProvider.GetCashFlow(20);
			return View(model);
		}

		public JsonResult GetCashFlow(string month, string nav)
		{
			//TODO: vvs p2 trace doesn't write to console
			Trace.WriteLine(string.Format("{0} {1}", month, nav));
			Debug.WriteLine(string.Format("Debug: {0} {1}", month, nav));

			if (string.IsNullOrEmpty(month))
			{
				month = DateTime.UtcNow.ToString("yyMM");
			}

			var dateYear = 2000 + int.Parse(month.Substring(0, 2));
			var dateMonth = int.Parse(month.Substring(2, 2));
			var date = new DateTime(dateYear, dateMonth, 1);
			switch (nav)
			{
				case "next": 
					date.AddMonths(1);
					break;
				case "prev": 
					date.AddMonths(-1);
					break;
				default:
					date = DateTime.Today;
					break;
			}
			//var cashFlow = FakeData.CashFlowProvider.GetCashFlow(10);
			component.GetCashFlow();
			var cashFlow = component.GetMonthCashFlow(date);
			var model = new CashFlowListModel(cashFlow);
			model.MonthValue = (int.Parse(model.MonthValue) + 1).ToString();
			return this.Json(model, JsonRequestBehavior.AllowGet);
		}
	}
}
